<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="标识符" prop="tag">
        <el-input
          v-model="queryParams.tag"
          placeholder="请输入标识符"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:dept:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :header-cell-style="{background: $store.state.app.theme.tableBack,color: $store.state.app.theme.tableColor}"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="渠道名称" width="150" />
      <el-table-column prop="deptId" label="渠道ID" width="100" />
      <el-table-column prop="status" label="派单状态" width="100">
        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.pdStatus == 1" class="item" effect="dark" content="正常" placement="right">
            <el-tag size="small">正常</el-tag>
          </el-tooltip>
          <el-tooltip v-if="scope.row.pdStatus == 0" class="item" effect="dark" :content="scope.row.pdStatustxt" placement="right">
            <el-tag size="small" type="danger">关闭</el-tag>
          </el-tooltip>
          <!-- <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/> -->
        </template>
      </el-table-column>
      <el-table-column prop="pdAmount" label="派单余额" width="100" />
      <el-table-column prop="tag" label="渠道码" width="100" />
      <el-table-column prop="type" label="类型" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 0" size="small">内部</el-tag>
          <el-tag v-if="scope.row.type == 1" size="small" type="warning">API</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="自动派单" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.zdpdStatus"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#bebdbf"
            @change="statusUp('zdpdStatus',scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="短信推送" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.smsStatus"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#bebdbf"
            @change="statusUp('smsStatus',scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="撞库开关" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.zkStatus"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#bebdbf"
            @change="statusUp('zkStatus',scope.row)"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="撞库开关" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            @change="statusUp('status',scope.row)"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#bebdbf">
          </el-switch>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:dept:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            v-hasPermi="['system:dept:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级渠道" prop="parentId">
          <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级渠道" />
        </el-form-item>
        <el-form-item label="渠道名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item label="派单余额" prop="pdAmount">
          <el-input v-model="form.pdAmount" placeholder="请输入派单余额" />
        </el-form-item>
        <el-form-item label="标识符" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入标识符" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入标识符" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option key="内部" value="0" label="内部">内部</el-option>
            <el-option key="api" value="1" label="api">api</el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.type ==1" label="url" prop="url">
          <el-input v-model="form.url" placeholder="请输入api地址" />
        </el-form-item>
        <el-form-item label="撞库开关" prop="zkStatus">
          <el-radio-group v-model="form.zkStatus">
            <el-radio label="1">开启</el-radio>
            <el-radio label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Dept',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined
      },
      // 表单参数
      form: {
        parentId: '',
        deptName: '',
        pdAmount: '',
        tag: '',
        leader: '',
        type: '',
        url: '',
        zkStatus: '1'
      },
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: '上级部门不能为空', trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        pdAmount: [
          { required: true, message: '派单余额不能为空', trigger: 'blur' }
        ],
        tag: [
          { required: true, message: '标识符不能为空', trigger: 'blur' }
        ],
        leader: [
          { required: true, message: '负责人不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: 'api地址不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true
      listDept(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, 'deptId')
        this.loading = false
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        parentId: '',
        deptName: '',
        pdAmount: '',
        tag: '',
        leader: '',
        type: '',
        url: '',
        zkStatus: '1'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row !== undefined) {
        this.form.parentId = row.deptId
      }
      this.open = true
      this.title = '添加渠道'
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const deptId = row.deptId || this.ids
      getDept(deptId).then(response => {
        this.loading = false
        this.form.deptId = response.data.deptId
        this.form.parentId = response.data.parentId
        this.form.deptName = response.data.deptName
        this.form.pdAmount = response.data.pdAmount
        this.form.tag = response.data.tag
        this.form.leader = response.data.leader
        this.form.type = String(response.data.type)
        this.form.url = response.data.url
        this.form.zkStatus = String(response.data.zkStatus)
        this.open = true
        this.title = '修改部门'
      })
      listDeptExcludeChild(row.deptId).then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    // 修改自动派单状态
    statusUp(tag, row) {
      const param = {
        deptId: row.deptId,
        parentId: row.parentId
      }
      if (tag === 'zdpdStatus') {
        param.zdpdStatus = row.zdpdStatus
      }
      if (tag === 'smsStatus') {
        param.smsStatus = row.smsStatus
      }
      if (tag === 'zkStatus') {
        param.zkStatus = row.zkStatus
      }
      // if(tag == 'status'){
      //   param.status = row.status
      // }
      updateDept(param).then(response => {
        if (response.code != '200') {
          this.$modal.msgError(response.msg)
          this.getList()
        } else {
          this.$modal.msgSuccess('修改成功')
          this.getList()
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.deptId !== undefined) {
            updateDept(this.form).then(response => {
              if (response.code != '200') {
                this.$modal.msgError(response.msg)
              } else {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addDept(this.form).then(response => {
              if (response.code != '200') {
                this.$modal.msgError(response.msg)
              } else {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function() {
        return delDept(row.deptId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    renderHeader(h, { column, $index }) {
      console.log(column)
      return [
        column.label,
        h(
          'el-tooltip',
          {
            props: {
              content: (function() {
                // return '效率值 = (周期内完成工单难度系数之和)/周期'
                // const label = column.label
                switch (column.property) {
                  case 'status':
                    return '关闭渠道状态会同步关闭渠道下管理员账号状态'
                }
              })(),
              placement: 'top'
            }
          },
          [
            h('span', {
              class: {
                'el-icon-question': true
              }
            })
          ]
        )
      ]
    }
  }
}
</script>
